// import https from "https";
// import fs from "fs";
// import path from "path";
const https = require('https');
const fs = require('fs');
const path = require('path');
function writeFile(targetFile, content) {
  const dir = path.dirname(targetFile);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  fs.writeFileSync(targetFile, content);
}

function numberToFixed(val) {
  return Math.round(val * 100 * 100) / 100 + '%';
  // return val.toFixed(4) * 100;
}

function getError(page) {
  var options = {
    hostname: 'analysis.oemsaas.shop',
    port: 443,
    path: '/allstore/realtime/err?caller=manager&token=ng5ujnxzpqo00&cart_error=1&error_type=js',
    method: 'GET',
  };

  var mData = '';
  var req = https.request(options, function (res) {
    res.setEncoding('utf-8');
    res.on('data', function (d) {
      mData += d;
    });
    res.on('end', function () {
      var data = JSON.parse(mData);

      // console.log('===================================data===========' + mData);
      if (data.code == '0') {
        // console.log(data.data.length);
        const error = {};
        data.data.forEach((element) => {
          if (element.hit_type_label) {
            try {
              const item = element.hit_type_label;
              if ( error[item.message]) {
                error[item.message].push(item);
              } else {
                error[item.message] = [item];
              }
              // if (
              //     item.message.search(
              //         /Unexpected end of script|Replace_with_Variable_Revenue_Function|LA|P is|EOF|_namespace|moi|Swiper|\$|waterfalls|quickview|oemsaasQuickview|oemcart_page_ca|omesaasProduct|addLazyImages|oemsaasSearch/g
              //     ) === -1
              // ) {
              //     error.push(item);
              // }
            } catch (error) {}
          }
        });
        const reportText =  Object.keys(error).map((key)=>{
          return  `${key}:错误数量：${error[key].length}`;
        }).join('\n');
        writeFile('./theme_error_list.json', JSON.stringify(error,null, 4));
        writeFile('./report.text', reportText);
      } else {
        console.log('请求失败：');
      }
    });
  });
  req.on('error', function (e) {
    console.error('====================================================' + e);
  });
  req.end();
}

getError();
